<template>
  <div class="gl_heightFull gl_contentBox">
    <div style="margin-bottom:15px">
      <el-button type="success" size="mini" @click="addstudent()">添加考生</el-button>
      <el-button v-loading="btnDownLoading" type="warning" size="mini" @click="exportpeople()">导出考生名单</el-button>
    </div>
    <div class="demo-input-suffix gl_searchBox">
      <el-row :gutter="20">
        <el-col :md="4" :lg="4">
          <p>会员费类型</p>
          <el-select v-model="IsEnabled" size="mini" @change="gettablelist()">
            <el-option label="全部" value="" />
            <el-option label="新增" value="New" />
            <el-option label="续费" value="Renew" />
          </el-select>
        </el-col>
        <el-col :md="4" :lg="4">
          <p>考生姓名</p>
          <el-input v-model="Api_GET_ClubDuanExamStudentQO.StudentName" placeholder="请输入考生名称" size="mini" clearable @change="gettablelist()" />
        </el-col>
        <el-col :md="4" :lg="4">
          <p>证件号码</p>
          <el-input v-model="Api_GET_ClubDuanExamStudentQO.IdCardNumber" placeholder="请输入证件号码" size="mini" clearable @change="gettablelist()" />
        </el-col>
        <el-col :md="4" :lg="4">
          <p>申报级别</p>
          <el-input v-model="Api_GET_ClubDuanExamStudentQO.DuanName" placeholder="请输入申报级别" size="mini" clearable @change="gettablelist()" />
        </el-col>
        <el-col :md="4" :lg="4">
          <p>教练</p>
          <el-input v-model="Api_GET_ClubDuanExamStudentQO.CoachName" placeholder="请输入教练名称" size="mini" clearable @change="gettablelist()" />
        </el-col>
        <el-col :md="4" :lg="4">
          <p>提交机构</p>
          <el-input v-model="Api_GET_ClubDuanExamStudentQO.OrganizationUnitName" placeholder="请输入提交机构名称" size="mini" clearable @change="gettablelist()" />
        </el-col>
        <el-col :md="4" :lg="4">
          <el-button type="primary" style="margin-top:25px" size="mini" @click="gettablelist()">筛选</el-button>
          <el-button type="warning" size="mini" @click="reset()">{{ $t('button.Reset') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <div style="margin-top:15px">
      <el-table v-loading="tableLoading" class="gl_table_noBorder" size="mini" :data="tableData">
        <el-table-column label="序号" type="index" align="center" width="55" />
        <el-table-column label="姓名" width="54">
          <template slot-scope="{row}">
            <!-- <img v-if="row.imagePath" class="roodsPhoto" :src="getStaticFileUrl(row.imagePath)" alt=""> -->
            <PersonalImage :imgurl="row.imagePath" imgheight="60px" />
          </template>
        </el-table-column>
        <el-table-column prop="studentName" />
        <el-table-column label="证件号" prop="idCardNumber" />
        <el-table-column label="联系方式" prop="phoneNumber" />
        <el-table-column label="当前级别" align="center">
          <template slot-scope="{row}">
            <span v-for="(item, index) in dict.duanType" :key="index">{{ item.code == row.duanTypeCode ? item.value : '' }}</span>
            {{ row.duanTypeCode !== null && row.levelTypeCode !== null ? '/':'' }}
            <span v-for="(item, index) in dict.levelType" :key="index + item">{{ item.code == row.levelTypeCode ? item.value : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申报级别" align="center">
          <template slot-scope="{row}">
            <span v-for="(item,index) in row.duanExamStudentDuans" :key="index">{{ item.duan.name }} {{ row.duanExamStudentDuans.length > 0 ? row.duanExamStudentDuans.length - 1 === index ? '': '/' : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="教练" align="center" prop="coachName" />
        <el-table-column label="会员费" align="center">
          <template slot-scope="{row}">
            <span v-if="row.memberFeeTypeCode !== null">
              {{ row.memberFeeTypeCode === 'New'?'新增':'续费' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="会员号" align="center" prop="memberNumber" />
        <el-table-column label="缴纳年限" align="center" prop="paymentYearTime" />
        <el-table-column label="申报金额" align="center">
          <template slot-scope="{ row }">
            <span>
              {{ parseFloat( row.requestAmount * 100) / 10000 }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="会费金额" align="center">
          <template slot-scope="{ row }">
            <span>
              {{ parseFloat( row.memberAmount * 100) / 10000 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="其他费用" align="center">
          <template slot-scope="{ row }">
            <span>
              {{ parseFloat( row.otherAmount * 100) / 10000 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="提交机构" align="center" prop="organizationUnitName" />
        <el-table-column label="考试成绩" align="center">
          <template slot-scope="{ row }">
            <span v-if="row.scoreStatusCode">
              {{ row.scoreStatusCode === 'Approved'?'通过':'不通过' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="100px"
        >
          <template slot-scope="{ row }">
            <el-button size="mini" type="text" @click="topersonal(row)">编辑</el-button>
            <el-button size="mini" type="text" @click="close(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="foot">
      <el-button size="mini" type="primary" @click="clickPay()">上传成绩单支付费用</el-button>
    </div>

    <!-- 支付方式弹出层 -->
    <el-dialog class="gl_dialog_TitleLine" title="选择支付方式" :visible.sync="dialogVisibleForPay" :close-on-click-modal="false" width="650px">
      <div v-loading="modalPayLoding" class="pay_type_list">
        <div v-if="paytype.isOpenOfflinePay" class="pay_type_item pay_type_offline gl_clear" @click="clickPayOffline()">线下支付</div>
        <div v-if="paytype.isOpenOnlinePay" class="pay_type_item pay_type_online gl_clear" @click="clickPayOnline()">线上支付</div>
      </div>
    </el-dialog>
    <form id="form" ref="form" action="https://unipay.ydfuture.com/api/v1/trade/cashDesk" method="post" style="display:none">
      <input ref="pay_params" type="text" name="pay_params" value="">
      <button type="submit">提交</button>
    </form>

    <el-dialog
      class="gl_dialog_TitleLine"
      title="线下收款账户信息"
      width="640px"
      :visible.sync="offlineDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <offline-pay-info :offline-data="offlineData" />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="jumpToOrderCenter">前往订单中心</el-button>
      </div>
    </el-dialog>

    <el-row class="gl_pt_15" style="text-align: right;">
      <el-pagination
        :current-page="Api_GET_ClubDuanExamStudentQO.Page"
        :page-size="Api_GET_ClubDuanExamStudentQO.MaxResultCount"
        :total="totalPage"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="sizeChange"
        @current-change="pageIndexChange"
      />
    </el-row>
  </div>
</template>

<script>
import PersonalImage from '@/components/PersonalImage/index';
import { mapState, mapActions } from 'vuex';
import OfflinePayInfo from '@/components/OfflinePayInfo';
import {
  Api_GET_TradePayOrderParameterQO
} from '@/lib/form/swaggerForm';
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { api_GET_ClubDuanExamStudent, api_GET_ClubDuanExamStudentScoreDuanExamPayInfoDuanExamId, api_DELETE_ClubDuanExamStudentId, api_POST_ClubDuanExamStudentScoreSubmitDuanExamReportDuanExamId } from '@/extend/api/hallswaggerApi/app.js';
import { Api_GET_ClubDuanExamStudentQO } from '@/lib/form/hall/swaggerForm';
import {
  api_GET_TradePersonalOrderCollectionCode, // 获取线下支付订单的收款码信息,
  api_GET_TradePayOrderParameter // 获取支付订单的参数
} from '@/extend/api/swaggerApi/app';
export default {
  components: {
    OfflinePayInfo,
    PersonalImage
  },
  data() {
    return {
      btnDownLoading: false,
      orderParameterQO: new Api_GET_TradePayOrderParameterQO(),
      paytype: {
        isOpenOnlinePay: false,
        isOpenOfflinePay: false
      }, // 支付方式
      topay: false,
      offlineData: {},
      offlineDialogVisible: false,
      GetStudentInput: {},
      modalPayLoding: false,
      tableData: [],
      IsEnabled: '',
      dialogVisibleForPay: false,
      totalPage: 0,
      orderNo: '', // 订单编号
      Api_GET_ClubDuanExamStudentQO: new Api_GET_ClubDuanExamStudentQO() // 考生数据
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      user: state => state.user.currentOU
    })
  },
  created() {
    this.getDict();
    this.gettablelist();
  },

  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    // 获取名单列表
    gettablelist(page) {
      this.tableLoading = true;
      this.Api_GET_ClubDuanExamStudentQO.IsApproved = true;
      this.Api_GET_ClubDuanExamStudentQO.IncludeDuanExamRequestDuans = true;
      this.Api_GET_ClubDuanExamStudentQO.IncludeRegisterStudent = true;
      this.Api_GET_ClubDuanExamStudentQO.MemberFeeTypeCode = this.IsEnabled;
      this.Api_GET_ClubDuanExamStudentQO.DuanExamId = this.$route.query.id;
      this.Api_GET_ClubDuanExamStudentQO.Sorting = 'creationTime DESC';
      this.Api_GET_ClubDuanExamStudentQO.Page = page || 1;
      this.Api_GET_ClubDuanExamStudentQO.SkipCount = (this.Api_GET_ClubDuanExamStudentQO.Page - 1) * this.Api_GET_ClubDuanExamStudentQO.MaxResultCount;
      console.log(this.Api_GET_ClubDuanExamStudentQO);
      api_GET_ClubDuanExamStudent(this.Api_GET_ClubDuanExamStudentQO).then(res => {
        this.totalPage = res.totalCount;
        this.tableData = res.items;
        this.tableLoading = false;
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 点击支付按钮
    clickPay () {
      if (this.tableData.length === 0) {
        this.$message({ type: 'warning', message: '未添加学员' });
        return;
      }
      api_GET_ClubDuanExamStudentScoreDuanExamPayInfoDuanExamId(this.$route.query.id).then(res => {
        if (res.isOpenOfflinePay === false && res.isOpenOnlinePay === false) {
          this.$message({ type: 'warning', message: '未设置收款账号' });
        } else {
          this.paytype = res;
          if (this.paytype.isOpenOfflinePay || this.paytype.isOpenOnlinePay) {
            // 单一支付方式直接跳转支付页面
            if (!(this.paytype.isOpenOfflinePay && this.paytype.isOpenOnlinePay)) {
              this.paytype.isOpenOfflinePay ? this.clickPayOffline() : this.clickPayOnline();
            } else {
              this.payLoading = false;
              this.dialogVisibleForPay = true;
            }
          } else {
            this.dialogVisibleForPay = true;
          }
        }
      }, error => {
        this.$message({ type: 'error', message: `订单创建失败！${error.error.message}` });
        this.dialogVisibleForPay = false;
        this.modalPayLoding = false;
      });
    },
    // 分页按钮
    sizeChange(MaxResultCount) {
      this.Api_GET_ClubDuanExamStudentQO.MaxResultCount = MaxResultCount;
      this.gettablelist();
    },
    pageIndexChange(currentPage) {
      this.gettablelist(currentPage);
    },
    // 重置按钮
    reset () {
      this.IsEnabled = '';
      this.Api_GET_ClubDuanExamStudentQO = new Api_GET_ClubDuanExamStudentQO();
      this.gettablelist();
    },
    // 删除按钮
    close(id) {
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_ClubDuanExamStudentId(id).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.gettablelist();
          }, error => {
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        });
    },
    // 添加考生
    addstudent() {
      this.$router.push({ name: 'addexamstudent', query: { id: this.$route.query.id }});
    },
    // 编辑考生
    topersonal(row) {
      console.log(row);
      this.$router.push({ name: 'addexamstudent', query: { id: this.$route.query.id, registerStudentId: row.id }});
    },
    exportpeople() {
      this.GetStudentInput.IncludeRegisterStudent = true;
      this.GetStudentInput.MemberFeeTypeCode = this.Api_GET_ClubDuanExamStudentQO.IsEnabled;
      this.GetStudentInput.DuanExamId = this.$route.query.id;
      this.GetStudentInput = JSON.stringify(this.GetStudentInput);
      var that = this;
      const tempUrl = `/api/excel`;
      const fileName = '考生' + '.xlsx';
      this.btnDownLoading = true;
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { reportName: 'DuanExamStudent', GetDuanExamStudentsInput: this.GetStudentInput }, WEB_CONFIG.VUE_APP_SWAGGER_HALL_BASE).then(res => {
        that.btnDownLoading = false;
        this.GetStudentInput = {};
      }).catch(error => {
        this.GetStudentInput = {};
        that.btnDownLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    // 线下支付
    clickPayOffline () {
      //  paytype: {
      //   isOpenOnlinePay: false,
      //   isOpenOfflinePay: false,
      // },
      if (!this.paytype.isOpenOfflinePay) {
        this.$message({ type: 'error', message: '未设置线下支付' });
        return;
      }
      this.topay = false;
      this.submitOrder();
    },
    clickPayOnline() {
      if (!this.paytype.isOpenOnlinePay) {
        this.$message({ type: 'error', message: '未设置线上支付' });
        return;
      }
      this.topay = true;
      this.submitOrder();
    },
    // 提交订单
    submitOrder() {
      const _json = {};

      if (this.topay) {
        // 如果是线上支付
        _json.isOnlinePayment = true;
      } else {
        // 线下支付，展示获取订单信息，展示收款账户信息
        _json.isOnlinePayment = false;
      }
      this.modalPayLoding = true;
      api_POST_ClubDuanExamStudentScoreSubmitDuanExamReportDuanExamId(this.$route.query.id, _json).then(res => {
        this.orderNo = res.orderNo;
        if (this.topay) {
        // 如果是线上支付
          this.payment(res.orderNo);
        } else {
        // 线下支付，展示获取订单信息，展示收款账户信息
          this.getOrderDetails(res.orderNo);
        }
        this.modalPayLoding = false;
      }, error => {
        this.$message({ type: 'error', message: `订单创建失败！${error.error.message}` });
        this.modalPayLoding = false;
      });
    },
    // 获取订单详情，用于线下支付展示收款账户信息
    getOrderDetails (orderNo) {
      api_GET_TradePersonalOrderCollectionCode({ orderNo: orderNo }).then(res => {
        res._orderNo = orderNo;
        this.offlineData = res;
        this.offlineDialogVisible = true;
      }).catch(error => {
        this.$message({ type: 'error', message: `订单详情获取失败！${error.error.message}` });
      });
    },
    // 去支付
    payment(orderNo) {
      if (orderNo) {
        const _origin = window.location.origin;
        const _pathname = window.location.pathname;
        // const _orderUrl = '#/myCenter/order';
        const _orderUrl = '#/' + this.$route.params.tenantId + '/order/expenditure/';
        const url = _origin + _pathname + _orderUrl;
        this.orderParameterQO.OrderNo = orderNo;
        this.orderParameterQO.ReturnUrl = url; // 支付成功后跳转的地址
        api_GET_TradePayOrderParameter(this.orderParameterQO)
          .then(res => {
            this.$refs.pay_params.value = res.parameter.replace(/\s*/g, '');
            this.$refs.form.submit();
          });
      }
    },
    jumpToOrderCenter() {
      this.$router.push({ name: 'Expenditure' });
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    }
  }

};
</script>

<style lang="scss" scoped>
.foot {
    margin-top: 15px;
    display: flex;
    justify-content: center;
}
.pay_type.van-popup {
  background-color: transparent;
  z-index: 3015 !important; /* 覆盖组件原有层级，避免与summary弹层冲突 */
}
.pay_type_list {
  display: flex;
  justify-content: space-around;
}
.pay_type_item {
  width: 260px;
  height: 84px;
  padding: 0 50px;
  margin-bottom: 12px;
  text-align: right;
  color: #fff;
  font-size: 24px;
  line-height: 84px;
  cursor: pointer;
}
.pay_type_item:last-child {
  margin-bottom: 0;
}
.pay_type_online {
  background-image: url('../../../../../assets/images/pay/online.png');
  background-repeat: no-repeat;
}
.pay_type_offline {
  background-image: url('../../../../../assets/images/pay/offline.png');
  background-repeat: no-repeat;
}
  .roodsPhoto{
    width: 60px;
    height: 60px;
    border-radius: 6px;
    vertical-align: middle;
  }
</style>
